package com.fjbdxk.beidou.bd;

import com.fjbdxk.beidou.RabbitMQExample;
import com.fjbdxk.beidou.SendExample;
import com.fjbdxk.beidou.core.AbstractBeiDouMessage;
import com.fjbdxk.beidou.core.ByteUtils;
import com.fjbdxk.beidou.msg.BDFKIMessage;
import com.fjbdxk.beidou.msg.CCTCQMessage;
import com.fjbdxk.beidou.net.SocketBeiDouNet;
import com.fjbdxk.beidou.redis.RedisUtil;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.logging.Logger;

/**
 * 发送示例
 *
 * @author huanggy
 * @version 1.0.0
 * @date 2024/05/13
 **/
public class SendExampleTest_2 {

    //分片发送参数
    public final static int part = RabbitMQExample.part * 2;//每段20字节，增加的话修改20的倍数
    private final static List<String> partInfo = new ArrayList<>();//缓存发送的段

    private static final Logger LOGGER = Logger.getLogger(SendExample.class.getName());

    private static int totalNum = 9;

    private static int startNum = 1;

    public static void main(String[] args) throws InterruptedException {
        // 使用网口通信
        SocketBeiDouNet socketBeiDouNet = new SocketBeiDouNet();
        socketBeiDouNet.open();//打开网络通信

        sendFile2(socketBeiDouNet);


    }

    //TP=1，负责发送数据。它包含一个无限循环 (while (true))，定期从 Redis 获取数据并构造待发送的报文
    public static   void sendFile2(SocketBeiDouNet socketBeiDouNet) throws InterruptedException {
        while (true) {
            List<TagConfig[]> data = getRedisByKeyNew1();
            //List<TagConfig[]> data = new ArrayList<>();
            //TagConfig[] tagConfig = PacketData.DEF_CONFIGS;  // 测点配置定义
            //data.add(tagConfig);
            // TagConfig[] tagConfig1 = PacketData.DEF_CONFIGS;  // 测点配置定义
            Date dt = new Date();  // 待发送时间周期的基准时间
            // 待发送报文设备（风机）集合
            Devices4Send devices = new Devices4Send( dt, 1);//封装待发送的设备数据，构造时传入当前时间和一个标识符
            if (devices.type != PacketHeader.TP.TP_2) {// 不是纯报警报文
                for (int i = 0; i < data.size(); ++i) {
                    // 一个设备待发送的数据集合
                    DeviceValues4Send values = new DeviceValues4Send(i);
                    for (int j = 1; j <= 10; ++j) {
                        double d = 10 * j + i;
                        values.addValue(data.get(i)[j - 1], d);
                    }
                    devices.addDeviceValues(values);
                }
            }

            TimeUnit.SECONDS.sleep(1);

            Date now = new Date();

            List listError = new LinkedList<>();
            // 制造两条故障报文
            PacketOption opt = new PacketOption(5, now, PacketOption.ET.ET_0.getValue(), 110);
            listError.add(opt);
            PacketOption opt2 = new PacketOption(9, now, PacketOption.ET.ET_0.getValue(), 210);
            listError.add(opt2);

            try {
                byte[] pack = devices.formatPack(listError);

                String s = ByteUtils.toHexString(pack).toUpperCase();

                // 打印分段发送的值
                //System.out.println("分段发送的值为：" + dataByRedis);
                // 创建CCTCQMessage对象
                CCTCQMessage msg = new CCTCQMessage(15950114, s);
                msg.setEncodeType(2);  // 设置编码类型
                System.out.println(msg.getMsg());  // 打印消息内容
                // 发送消息并接收响应
                BDFKIMessage res = (BDFKIMessage) socketBeiDouNet.sendMessage(msg);
                // 打印响应信息
                System.out.println(res == null ? "N" : (res.getResult() + ":" + res.getFailResult()));
                //Thread.sleep(60000);  // 线程休眠55秒
            } catch (Exception e) {
                throw new RuntimeException(e);
            }



        }
    }

    //TP=0
    public static   void sendFile1(SocketBeiDouNet socketBeiDouNet) throws InterruptedException {
        while (true) {
            List<TagConfig[]> data = getRedisByKeyNew();
            //List<TagConfig[]> data = new ArrayList<>();
            //TagConfig[] tagConfig = PacketData.DEF_CONFIGS;  // 测点配置定义
            //data.add(tagConfig);
           // TagConfig[] tagConfig1 = PacketData.DEF_CONFIGS;  // 测点配置定义
            Date dt = new Date();  // 待发送时间周期的基准时间
            // 待发送报文设备（风机）集合
            Devices4Send devices = new Devices4Send( dt, 0);
            if (devices.type != PacketHeader.TP.TP_2) {// 不是纯报警报文
                for (int i = 0; i < data.size(); ++i) {
                    // 一个设备待发送的数据集合
                    DeviceValues4Send values = new DeviceValues4Send(i);
                    for (int j = 1; j <= 10; ++j) {
                        double d = 10 * j + i;
                        values.addValue(data.get(i)[j - 1], d);
                    }
                    devices.addDeviceValues(values);
                }
            }

            TimeUnit.SECONDS.sleep(1);

            Date now = new Date();

            List listError = new LinkedList<>();
            // 制造两条故障报文
            PacketOption opt = new PacketOption(5, now, PacketOption.ET.ET_0.getValue(), 110);
            listError.add(opt);
            PacketOption opt2 = new PacketOption(9, now, PacketOption.ET.ET_0.getValue(), 210);
            listError.add(opt2);

            try {
                byte[] pack = devices.formatPack(listError);

                String s = ByteUtils.toHexString(pack).toUpperCase();

                // 打印分段发送的值
                //System.out.println("分段发送的值为：" + dataByRedis);
                // 创建CCTCQMessage对象
                CCTCQMessage msg = new CCTCQMessage(15950114, s);
                msg.setEncodeType(2);  // 设置编码类型
                System.out.println(msg.getMsg());  // 打印消息内容
                // 发送消息并接收响应
                BDFKIMessage res = (BDFKIMessage) socketBeiDouNet.sendMessage(msg);
                // 打印响应信息
                System.out.println(res == null ? "N" : (res.getResult() + ":" + res.getFailResult()));
                Thread.sleep(60000);  // 线程休眠55秒
            } catch (Exception e) {
                throw new RuntimeException(e);
            }



        }
    }



    private static List<TagConfig[]> getRedisByKeyNew() {
        List<TagConfig[]> data1 = new ArrayList<>();
        for (int i = startNum; i <= startNum+totalNum; i++) {
            String incremented = String.format("%03d", i);
            System.out.println("当前incremented："+incremented);
            String hashKey = "Wec:Jinzixian"+incremented+":TagVal";

            String[] data = new String[10];
            //PLC状态：
            data[0] = new RedisUtil().getHashValue("WecPlcSt");
            //温度：NacOutTmp
            data[1] = new RedisUtil().getHashValue(hashKey,"NacOutTmp");
            //风速：NacWdSpdFltS
            data[2] = new RedisUtil().getHashValue(hashKey,"NacWdSpdFltS");

            //功率：CnvW（有功功率）(float)
            data[3] = new RedisUtil().getHashValue(hashKey,"CnvW");

            //转矩：CnvTorq（转矩）(float)(double)
            data[4] = new RedisUtil().getHashValue(hashKey,"CnvTorq");

            //发电机转速：GenSpd（发电机转速）(float)(int)
            data[5] = new RedisUtil().getHashValue(hashKey,"GenSpd");

            //叶轮转速：RotSpd（风轮转速）(float)
            data[6] = new RedisUtil().getHashValue(hashKey,"RotSpd");

            //风向：NacWdDir（风向）(float)(double)
            data[7] = new RedisUtil().getHashValue(hashKey,"NacWdDir");

            //桨距角
            data[8] = new RedisUtil().getHashValue("PtAngSetBl1");

            //发电量：WecWh（总发电量）(int)
            data[9] = new RedisUtil().getHashValue(hashKey,"WecWh");

            TagConfig[] DEF_CONFIGS;
            DEF_CONFIGS = new TagConfig[10];
            DEF_CONFIGS[0] = new TagConfig(1, 1, Double.parseDouble(data[0]));
            DEF_CONFIGS[1] = new TagConfig(1, 1, Double.parseDouble(data[1]));
            DEF_CONFIGS[2] = new TagConfig(2, 0.01, Double.parseDouble(data[2]));
            DEF_CONFIGS[3] = new TagConfig(2, 1, Double.parseDouble(data[3]));
            DEF_CONFIGS[4] = new TagConfig(2, 0.1, Double.parseDouble(data[4]));
            DEF_CONFIGS[5] = new TagConfig(2, 1, Double.parseDouble(data[5]));
            DEF_CONFIGS[6] = new TagConfig(2, 0.01, Double.parseDouble(data[6]));
            DEF_CONFIGS[7] = new TagConfig(2, 0.1, Double.parseDouble(data[7]));
            DEF_CONFIGS[8] = new TagConfig(2, 0.1, Double.parseDouble(data[8]));
            DEF_CONFIGS[9] = new TagConfig(4, 1, Double.parseDouble(data[9]));
            //data1.add(data);
            data1.add(DEF_CONFIGS);
            System.out.println("读取key："+hashKey);
            System.out.println("读取key的值结束数量：："+data.length);
        }


        return data1;

    }

    private static List<TagConfig[]> getRedisByKeyNew1() {
        List<TagConfig[]> data1 = new ArrayList<>();
        for (int i = 1; i <= 10; i++) {
            int read = 1;
            String incremented = String.format("%03d", read);
            System.out.println("当前incremented："+incremented);
            String hashKey = "Wec:Jinzixian"+incremented+":TagVal";

            String[] data = new String[10];
            //PLC状态：
            data[0] = new RedisUtil().getHashValue("WecPlcSt");
            //温度：NacOutTmp
            data[1] = new RedisUtil().getHashValue(hashKey,"NacOutTmp");
            //风速：NacWdSpdFltS
            data[2] = new RedisUtil().getHashValue(hashKey,"NacWdSpdFltS");

            //功率：CnvW（有功功率）(float)
            data[3] = new RedisUtil().getHashValue(hashKey,"CnvW");

            //转矩：CnvTorq（转矩）(float)(double)
            data[4] = new RedisUtil().getHashValue(hashKey,"CnvTorq");

            //发电机转速：GenSpd（发电机转速）(float)(int)
            data[5] = new RedisUtil().getHashValue(hashKey,"GenSpd");

            //叶轮转速：RotSpd（风轮转速）(float)
            data[6] = new RedisUtil().getHashValue(hashKey,"RotSpd");

            //风向：NacWdDir（风向）(float)(double)
            data[7] = new RedisUtil().getHashValue(hashKey,"NacWdDir");

            //桨距角
            data[8] = new RedisUtil().getHashValue("PtAngSetBl1");

            //发电量：WecWh（总发电量）(int)
            data[9] = new RedisUtil().getHashValue(hashKey,"WecWh");

            TagConfig[] DEF_CONFIGS;
            DEF_CONFIGS = new TagConfig[10];
            DEF_CONFIGS[0] = new TagConfig(1, 1, Double.parseDouble(data[0]));
            DEF_CONFIGS[1] = new TagConfig(1, 1, Double.parseDouble(data[1]));
            DEF_CONFIGS[2] = new TagConfig(2, 0.01, Double.parseDouble(data[2]));
            DEF_CONFIGS[3] = new TagConfig(2, 1, Double.parseDouble(data[3]));
            DEF_CONFIGS[4] = new TagConfig(2, 0.1, Double.parseDouble(data[4]));
            DEF_CONFIGS[5] = new TagConfig(2, 1, Double.parseDouble(data[5]));
            DEF_CONFIGS[6] = new TagConfig(2, 0.01, Double.parseDouble(data[6]));
            DEF_CONFIGS[7] = new TagConfig(2, 0.1, Double.parseDouble(data[7]));
            DEF_CONFIGS[8] = new TagConfig(2, 0.1, Double.parseDouble(data[8]));
            DEF_CONFIGS[9] = new TagConfig(4, 1, Double.parseDouble(data[9]));
            //data1.add(data);
            data1.add(DEF_CONFIGS);
            System.out.println("读取key："+hashKey);
            System.out.println("读取key的值结束数量：："+data.length);
            try {
                Thread.sleep(6000);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }

        System.out.println("1分钟读取的数据"+data1);

        return data1;

    }
}
